package com.atmilan.quartz.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.atmilan.quartz.constant.Constants;
import com.atmilan.quartz.mapper.StoreProductLuxuryMapper;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttrResult;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttrValue;
import com.atmilan.quartz.model.entity.crmeb.StoreProductCate;
import com.atmilan.quartz.model.entity.crmeb.StoreProductCoupon;
import com.atmilan.quartz.model.entity.crmeb.StoreProductDescription;
import com.atmilan.quartz.service.IStoreProductAttrResultService;
import com.atmilan.quartz.service.IStoreProductAttrService;
import com.atmilan.quartz.service.IStoreProductAttrValueService;
import com.atmilan.quartz.service.IStoreProductCateService;
import com.atmilan.quartz.service.IStoreProductCouponService;
import com.atmilan.quartz.service.IStoreProductDescriptionService;
import com.atmilan.quartz.service.IStoreProductLuxuryService;
import com.atmilan.quartz.service.ISystemAttachmentService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
// TODO 未知错误, 行数227, 不会切换回数据库, 待排查
@DS("luxury")
public class StoreProductLuxuryServiceImpl extends ServiceImpl<StoreProductLuxuryMapper, StoreProduct> implements IStoreProductLuxuryService {
    @Autowired
    private StoreProductLuxuryMapper storeProductLuxuryMapper;
    @Autowired
    private ISystemAttachmentService systemAttachmentService;
    @Autowired
    private IStoreProductAttrService storeProductAttrService;
    @Autowired
    private IStoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private IStoreProductAttrResultService storeProductAttrResultService;
    @Autowired
    private IStoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    private IStoreProductCouponService storeProductCouponService;
    @Autowired
    private IStoreProductCateService storeProductCateService;

    
    /**
     * 新增产品
     * @param storeProductCrmebRequest 新增产品request对象
     * @return 新增结果
     */
    @Override
    public boolean save(StoreProductCrmebRequest storeProductCrmebRequest) {
        StoreProduct storeProduct = new StoreProduct();
        BeanUtils.copyProperties(storeProductCrmebRequest, storeProduct);
        storeProduct.setCreateTime(new Date());

        //主图
        storeProduct.setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()));
        //轮播图
        storeProduct.setSliderImage(systemAttachmentService.clearPrefix(storeProduct.getSliderImage()));
        //计算价格
        calcPriceForAttrValues(storeProductCrmebRequest, storeProduct);

        //保存数据
        boolean save = save(storeProduct);
        if (null != storeProduct.getId()) {
            storeProductCrmebRequest.setId(storeProduct.getId());
        }
        if (storeProductCrmebRequest.getSpecType()) { // 多属性
            storeProductCrmebRequest.getAttr().forEach(e -> {
                e.setProductId(storeProduct.getId());
                e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
            });
            boolean attrAddResult = storeProductAttrService.saveBatch(storeProductCrmebRequest.getAttr());
            if (!attrAddResult) {
                log.warn("新增属性名失败");
            }
        } else { // 单属性
            StoreProductAttr singleAttr = new StoreProductAttr();
            singleAttr.setProductId(storeProduct.getId()).setAttrName("规格").setAttrValues("默认").setType(0);
            boolean attrAddResult = storeProductAttrService.save(singleAttr);
            if (!attrAddResult) {
                log.warn("新增属性名失败");
            }
            StoreProductAttrValue singleAttrValue = new StoreProductAttrValue();
            BigDecimal commissionL1 = BigDecimal.ZERO;
            BigDecimal commissionL2 = BigDecimal.ZERO;
            if (storeProductCrmebRequest.getAttrValue().size() > 0) {
                commissionL1 = null != storeProductCrmebRequest.getAttrValue().get(0).getBrokerage() ? storeProductCrmebRequest.getAttrValue().get(0).getBrokerage() : BigDecimal.ZERO;
                commissionL2 = null != storeProductCrmebRequest.getAttrValue().get(0).getBrokerageTwo() ? storeProductCrmebRequest.getAttrValue().get(0).getBrokerageTwo() : BigDecimal.ZERO;
            }

            singleAttrValue.setProductId(storeProduct.getId()).setStock(storeProduct.getStock()).setSuk("默认").setSales(storeProduct.getSales()).setPrice(storeProduct.getPrice()).setImage(systemAttachmentService.clearPrefix(storeProduct.getImage())).setCost(storeProduct.getCost()).setBarCode(storeProduct.getBarCode()).setOtPrice(storeProduct.getOtPrice()).setBrokerage(commissionL1).setBrokerageTwo(commissionL2);
            boolean saveOrUpdateResult = storeProductAttrValueService.save(singleAttrValue);
            if (!saveOrUpdateResult) {
                log.warn("新增属性详情失败");
            }
        }
        if (null != storeProductCrmebRequest.getAttrValue() && storeProductCrmebRequest.getAttrValue().size() > 0) {
            // 批量设置attrValues对象的商品id
            List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = storeProductCrmebRequest.getAttrValue();
            storeProductAttrValuesRequest.forEach(e -> {
                e.setProductId(storeProduct.getId());
            });
            List<StoreProductAttrValue> storeProductAttrValues = new ArrayList<>();
            for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
                StoreProductAttrValue spav = new StoreProductAttrValue();
                BeanUtils.copyProperties(attrValuesRequest, spav);
                //设置sku字段
                if (null == attrValuesRequest.getAttrValue()) {
                    break;
                }
                List<String> skuList = new ArrayList<>();
                for (Map.Entry<String, String> vo : attrValuesRequest.getAttrValue().entrySet()) {
                    skuList.add(vo.getValue());
                    spav.setSuk(String.join(",", skuList));
                }
                spav.setImage(systemAttachmentService.clearPrefix(spav.getImage()));
                spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                storeProductAttrValues.add(spav);
            }
            // 保存属性
            if (storeProductAttrValues.size() > 0) {
                boolean saveOrUpdateResult = storeProductAttrValueService.saveBatch(storeProductAttrValues);
                StoreProductAttrResult attrResult = new StoreProductAttrResult(/*0, */storeProduct.getId(), systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductCrmebRequest.getAttrValue())), Integer.parseInt(String.valueOf(System.currentTimeMillis()/1000L)), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
                storeProductAttrResultService.save(attrResult);
                if (!saveOrUpdateResult) {
                    log.warn("新增属性详情失败");
                }
            }
        }

        // 处理富文本
        StoreProductDescription dbDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
        		.eq(StoreProductDescription :: getProductId, storeProduct.getId())
        		.last("LIMIT 1")
        		);
        StoreProductDescription storeProductDescription = StoreProductDescription.getDescriptionByProduct(storeProduct);
        storeProductDescription.setId(ObjectUtil.isNotNull(dbDescription) ? dbDescription.getId() : null);
        storeProductDescription.setProductId(storeProduct.getId());
        storeProductDescriptionService.saveOrUpdate(storeProductDescription);

        // 处理优惠券关联信息
        shipProductCoupons(storeProductCrmebRequest, storeProduct);
        return save;
    }

    /**
     * 更新产品
     * @param storeProductCrmebRequest 更新产品request对象
     * @return 更新结果
     */
    @Override
    public boolean update(StoreProductCrmebRequest storeProductCrmebRequest) {
        StoreProduct storeProduct = new StoreProduct();
        BeanUtils.copyProperties(storeProductCrmebRequest, storeProduct);
        storeProduct.setCreateTime(new Date());

        //主图
        storeProduct.setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()));

        //轮播图
        storeProduct.setSliderImage(systemAttachmentService.clearPrefix(storeProduct.getSliderImage()));

        calcPriceForAttrValues(storeProductCrmebRequest, storeProduct);
        boolean saveCount = updateById(storeProduct);
        
        // 对attr表做全量更新，删除原有数据保存现有数据
        storeProductAttrService.removeByProductId(storeProduct.getId());
//        List<StoreProductAttrValue> attrValuelist = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId, storeProduct.getId()));
//        Map<String, StoreProductAttrValue> attrValueMap = attrValuelist == null ? MapUtil.newHashMap() : attrValuelist.stream().collect(Collectors.toMap(StoreProductAttrValue::getSuk, Function.identity()));
        if (CollectionUtils.isNotEmpty(storeProductCrmebRequest.getAttrValue())) {
            for(StoreProductAttrValueRequest attrValueRequest : storeProductCrmebRequest.getAttrValue()) {
                if (null != attrValueRequest.getAttrValue()) {
                    List<String> skuList = new ArrayList<>();
                    for (Map.Entry<String, String> vo : attrValueRequest.getAttrValue().entrySet()) {
                        skuList.add(vo.getValue());
                    }
                    attrValueRequest.setSuk(String.join(",", skuList));
//                    attrValueRequest.setId(attrValueMap.containsKey(attrValueRequest.getSuk()) ? attrValueMap.get(attrValueRequest.getSuk()).getId() : null);
                }
            
                
            }
//            storeProductCrmebRequest.getAttrValue().forEach(attrValueRequest -> {
//                if (null != attrValueRequest.getAttrValue()) {
//                    List<String> skuList = new ArrayList<>();
//                    for (Map.Entry<String, String> vo : attrValueRequest.getAttrValue().entrySet()) {
//                        skuList.add(vo.getValue());
//                    }
//                    attrValueRequest.setSuk(String.join(",", skuList));
//                    attrValueRequest.setId(attrValueMap.containsKey(attrValueRequest.getSuk()) ? attrValueMap.get(attrValueRequest.getSuk()).getId() : null);
//                }
//            });
        }

        if (storeProductCrmebRequest.getSpecType()) { //  确认单属性商品的attr参数
            storeProductCrmebRequest.getAttr().forEach(e -> {
                e.setProductId(storeProductCrmebRequest.getId());
                e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
            });
            storeProductAttrService.saveBatch(storeProductCrmebRequest.getAttr());
            if (CollectionUtils.isNotEmpty(storeProductCrmebRequest.getAttrValue())) {
                storeProductAttrValueService.removeByProductId(storeProduct.getId());

                List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = storeProductCrmebRequest.getAttrValue();
                // 批量设置attrValues对象的商品id
                storeProductAttrValuesRequest.forEach(e -> e.setProductId(storeProductCrmebRequest.getId()));
                List<StoreProductAttrValue> storeProductAttrValues = new ArrayList<>();
                for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
                    StoreProductAttrValue spav = new StoreProductAttrValue();
                    BeanUtils.copyProperties(attrValuesRequest, spav);
                    spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                    storeProductAttrValues.add(spav);
                }
                boolean saveOrUpdateResult = storeProductAttrValueService.saveBatch(storeProductAttrValues);
                // attrResult整存整取，不做更新
                storeProductAttrResultService.remove(Wrappers.<StoreProductAttrResult>lambdaQuery()
                        .eq(StoreProductAttrResult :: getProductId, storeProduct.getId())
                        );
                
                StoreProductAttrResult attrResult = new StoreProductAttrResult(/*0,*/ storeProduct.getId(), systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductCrmebRequest.getAttrValue())), Integer.parseInt(String.valueOf(System.currentTimeMillis()/1000L)), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
                storeProductAttrResultService.save(attrResult);
                if (!saveOrUpdateResult) {
                    log.warn("编辑属性详情失败");
                }

            }
        } else {
            StoreProductAttr singleAttr = new StoreProductAttr();
            singleAttr.setProductId(storeProduct.getId()).setAttrName("规格").setAttrValues("默认").setType(0);
            boolean attrAddResult = storeProductAttrService.save(singleAttr);
            if (!attrAddResult) {
                log.warn("新增属性名失败");
            }
            StoreProductAttrValue singleAttrValue = new StoreProductAttrValue();
            if (storeProductCrmebRequest.getAttrValue().size() == 0) {
                log.warn("attrValue不能为空");
            }
            StoreProductAttrValueRequest attrValueRequest = storeProductCrmebRequest.getAttrValue().get(0);
            BeanUtils.copyProperties(attrValueRequest, singleAttrValue);
            singleAttrValue.setProductId(storeProduct.getId());
            singleAttrValue.setSuk("默认");
            singleAttrValue.setImage(systemAttachmentService.clearPrefix(singleAttrValue.getImage()));
            storeProductAttrValueService.removeByProductId(storeProduct.getId());
            boolean saveOrUpdateResult = storeProductAttrValueService.save(singleAttrValue);
            if (!saveOrUpdateResult) {
                log.warn("新增属性详情失败");
            }
        }

        // 处理分类辅助表
        if (null != storeProductCrmebRequest.getCateIds()) {
            for (int i = 0; i < storeProductCrmebRequest.getCateIds().size(); i++) {
                Integer cateid = storeProductCrmebRequest.getCateIds().get(i);
                StoreProductCate storeProductCate = new StoreProductCate(storeProduct.getId(), cateid, Integer.parseInt(String.valueOf(System.currentTimeMillis()/1000L)));
                LambdaUpdateWrapper<StoreProductCate> luw = new LambdaUpdateWrapper<>();
                luw.set(StoreProductCate::getProductId, storeProductCate.getProductId());
                luw.set(StoreProductCate::getCateId, storeProductCate.getCateId());
                luw.set(StoreProductCate::getAddTime, storeProductCate.getAddTime());
                storeProductCateService.update(luw);
            }
        }

        // 处理富文本
        StoreProductDescription dbDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
        		.eq(StoreProductDescription :: getProductId, storeProduct.getId())
        		.last("LIMIT 1")
        		);
        StoreProductDescription storeProductDescription = StoreProductDescription.getDescriptionByProduct(storeProduct);
        storeProductDescription.setId(ObjectUtil.isNotNull(dbDescription) ? dbDescription.getId() : null);
        storeProductDescription.setProductId(storeProduct.getId());
        storeProductDescriptionService.saveOrUpdate(storeProductDescription);
        
        //productSearchService.updateProductData(storeProduct.getId());
        // 处理优惠券关联信息
        shipProductCoupons(storeProductCrmebRequest, storeProduct);
        return saveCount;
    }

    @Override
    public StoreProduct getByBarCode(String barCode) {
        return getOne(Wrappers.<StoreProduct>lambdaQuery()
                .eq(StoreProduct::getBarCode, barCode)
                .last("LIMIT 1")
                );
    }
    
    /**
     * 计算产品属性之中最大和最小的价格，新增和编辑使用
     * @param storeProductCrmebRequest 分析的参数
     * @param storeProduct 当前操作的产品
     */
    private void calcPriceForAttrValues(StoreProductCrmebRequest storeProductCrmebRequest, StoreProduct storeProduct) {
        // 不要显示成本价，显示最低sku售价
        double costPrice = storeProductCrmebRequest.getAttrValue()
                .stream().mapToDouble(e->e.getCost().doubleValue()).min().getAsDouble();

        //原成本价
        BigDecimal sourceCost = storeProductCrmebRequest.getSourceCost();

        double sellPrice = storeProductCrmebRequest.getAttrValue()
                .stream().mapToDouble(e->e.getPrice().doubleValue()).min().getAsDouble();
        // 原价
        double otPrice = storeProductCrmebRequest.getAttrValue()
                .stream().mapToDouble(e->e.getOtPrice().doubleValue()).min().getAsDouble();

        int stock = storeProductCrmebRequest.getAttrValue()
                    .stream().mapToInt(e->e.getStock()).sum();
        storeProduct.setCost(BigDecimal.valueOf(costPrice));
        storeProduct.setSourceCost(sourceCost);
        storeProduct.setPrice(BigDecimal.valueOf(sellPrice));
        storeProduct.setOtPrice(BigDecimal.valueOf(otPrice));
        storeProduct.setStock(stock);
    }
    
    /**
     * 设置优惠券信息
     * @param storeProductRequest 商品request信息
     * @param storeProduct 商品信息
     */
    private void shipProductCoupons(StoreProductCrmebRequest storeProductCrmebRequest, StoreProduct storeProduct) {
        if(null != storeProductCrmebRequest.getCouponIds() && storeProductCrmebRequest.getCouponIds().size() > 0){
            storeProductCouponService.deleteByProductId(storeProduct.getId());
            List<StoreProductCoupon> spcs = new ArrayList<>();
            for (Integer couponId : storeProductCrmebRequest.getCouponIds()) {
                StoreProductCoupon spc = new StoreProductCoupon(storeProduct.getId(), couponId, Integer.parseInt(String.valueOf(System.currentTimeMillis()/1000L)));
                spcs.add(spc);
            }
            storeProductCouponService.saveCoupons(spcs);
        }
    }

    @Override
    public void deleteAll() {
        storeProductLuxuryMapper.deleteAll();
    }
    
}
